package com.cmwa.scbp.business.customerEquity.estimate.service.impl;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.stereotype.Service;

import com.cmwa.scbp.business.customerEquity.estimate.dao.EstimateInfoDao;
import com.cmwa.scbp.business.customerEquity.estimate.entity.EstimateInfoVo;
import com.cmwa.scbp.business.customerEquity.estimate.service.EstimateInfoService;
import com.cmwa.scbp.business.myHome.todo.dao.TodoDao;
import com.cmwa.scbp.business.myHome.todo.entity.TodoVo;
import com.cmwa.scbp.base.mvc.entity.Page;
import com.cmwa.scbp.base.mvc.entity.SearchParam;
import com.cmwa.scbp.sys.attach.dao.AttachDao;
import com.cmwa.scbp.sys.attach.entity.AttachVo;
import com.cmwa.scbp.utils.SQLUtil;
import com.cmwa.scbp.utils.SessionUtils;

/**
 * 估值表业务实现层
 * 
 * @author ex-zhengqq
 * @date 2019-01-23 13:34:46
 */
@Service
public class EstimateInfoServiceImpl implements EstimateInfoService {
	@Resource
	private EstimateInfoDao estimateInfoDao;
	@Resource
	private AttachDao attachDao;
	@Resource
	private TodoDao todoDao;
	
	public void insertEstimateInfo(EstimateInfoVo estimateInfo) {
		String empId = SessionUtils.getEmployee().getID();
		estimateInfo.setCreateId(empId);
		estimateInfo.setStatus("S");
		estimateInfoDao.insertEstimateInfo(estimateInfo);
	}
	
	public void physicDeleteEstimateInfoById(String id) {
		estimateInfoDao.physicDeleteEstimateInfoById(id);
	}
	
	public void logicDeleteEstimateInfoById(String id) {
		estimateInfoDao.logicDeleteEstimateInfoById(id);
	}
	
	public void updateEstimateInfoById(EstimateInfoVo estimateInfo) {
		estimateInfoDao.updateEstimateInfoById(estimateInfo);
	}
	
	public EstimateInfoVo getEstimateInfoById(String id) {
		return estimateInfoDao.getEstimateInfoById(id);
	}
	
	public Page<EstimateInfoVo> estimateInfoListPage(SearchParam sp) {
		if(SessionUtils.getEmployee().getEmpType().equalsIgnoreCase("OUT")){
			sp.getSp().put("empId", SessionUtils.getEmployee().getID());
		}
		List<EstimateInfoVo> items = estimateInfoDao.estimateInfoListPage(sp);
		return Page.create(items, sp.getStart(), sp.getLimit(), sp.getTotal());
	}
	
	@Override
	public void addAttachRel(EstimateInfoVo estimateInfoVo){
		String empId = SessionUtils.getEmployee().getID();
		String attIds = estimateInfoVo.getAttIds();
		if(StringUtils.isNotBlank(attIds)) {
			/*String[] split = attIds.split(",");
			String newAttIds = "";
			for (String attId : split) {
				AttachVo av = attachDao.findAttachAndRelByAttId(attId);
				if(av == null) {
					newAttIds += attId+",";
				}
			}*/
			//估值材料 "ESTIMATE_DATA"
			//估值文件 "ESTIMATE_FILE"
			attachDao.addAttachRel2(empId, estimateInfoVo.getEstimateId(), 
					estimateInfoVo.getAttSource(), attIds);
		}
	}
	
	@Override
	public List<Map<String, String>> countReportData(String reprotDateBgn, String reprotDateEnd){
		List<Map<String, String>> map = null;
		String empId = "";
		if(StringUtils.isNotBlank(reprotDateBgn) && StringUtils.isNotBlank(reprotDateEnd)){
			if(SessionUtils.getEmployee().getEmpType().equalsIgnoreCase("OUT")){
				empId = SessionUtils.getEmployee().getID();
			}
			reprotDateBgn = reprotDateBgn.replaceAll("/", "-");
			reprotDateEnd = reprotDateEnd.replaceAll("/", "-");
			map = estimateInfoDao.countReportData(reprotDateBgn,reprotDateEnd,empId);
		}
		return map;
	}

	@Override
	public List<String> getAttachByIdEstimateData(String[] id) {
		return estimateInfoDao.getAttachByIdEstimateData(id);
	}

	@Override
	public List<String> getAttachByIdEstimateFile(String[] id) {
		return estimateInfoDao.getAttachByIdEstimateFile(id);
	}

	@Override
	public void updateEstimateInfo(EstimateInfoVo estimateInfoVo) {
		TodoVo todoVo = new TodoVo();
		todoVo.setPrjCode(estimateInfoVo.getPrjCode());
		todoVo.setStatus("S");
		todoVo.setModifyId(SessionUtils.getEmployee().getID());
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			todoVo.setTodoDate(sdf.parse(estimateInfoVo.getReportTime()));
			todoDao.updateTodoByProduct(todoVo);//更新对应估值表信息
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public List<AttachVo> queryAttInfoById(String estimateId,String type) {
		return estimateInfoDao.queryAttInfoById(estimateId,type);
	}

	@Override
	public String getAttachByDateEstimateFile(String startDate, String endDate) {
		String empId = "";
		if(SessionUtils.getEmployee().getEmpType().equalsIgnoreCase("OUT")){
			empId = SessionUtils.getEmployee().getID();
		}
		return estimateInfoDao.getAttachByDateEstimateFile(startDate,endDate,empId);
	}

	@Override
	public void deleteAttach(String estimateId, String attSource) {
		if(StringUtils.isNotBlank(estimateId) && StringUtils.isNotBlank(attSource)) {
			attachDao.deleteAttachRel2(estimateId,attSource);
		}
	}
	@Override
	public void downloadAttachZip(List<AttachVo> attList, OutputStream out,String isBatch) throws Exception {
		Map<String,List<AttachVo>> map = new HashMap<String,List<AttachVo>>();
		for(AttachVo AttachVo:attList) {
			String getPrjSName = AttachVo.getPrjSName();
			//特殊处理为空数据
			if(StringUtils.isBlank(getPrjSName)) {
				getPrjSName = "-";
			}
			if(map.containsKey(getPrjSName)) {
				map.get(getPrjSName).add(AttachVo);
				map.put(getPrjSName, map.get(getPrjSName));
			}else {
				List<AttachVo> list = new ArrayList<AttachVo>();
				list.add(AttachVo);
				map.put(getPrjSName, list);
			}
		}
		ZipOutputStream outZip = new ZipOutputStream(out);
		try {
			for (Map.Entry<String,List<AttachVo>> entry : map.entrySet()) {
				List<AttachVo> list = entry.getValue();
				if(CollectionUtils.isNotEmpty(list)) {
					for (int i = 0; i < list.size(); i++) {
						String reportTime = list.get(i).getReportTime();
						if("Y".equals(isBatch)) {
							outZip.putNextEntry(new ZipEntry(entry.getKey()+reportTime+"/"+list.get(i).getAttName()));
						}else {
							outZip.putNextEntry(new ZipEntry(list.get(i).getAttName()));
						}
						outZip.setEncoding("UTF-8");
						FileInputStream fis1 = null;
						try {
							fis1 = new FileInputStream(list.get(i).getAttPath());
							if(fis1!=null){
								byte[] buffer1 = new byte[1024];
								int byteread1 = 0;
								// 写入zip包
								while ((byteread1 = fis1.read(buffer1)) != -1) {
									outZip.write(buffer1, 0, byteread1);
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}finally{
							if(fis1!=null){
								fis1.close();
							}
						}
					}
				}
			}
		} catch (Exception ex2) {
			ex2.printStackTrace();
			throw new Exception("关闭大对象异常");
		}finally{
			if (outZip != null) {
				outZip.flush();
				outZip.close();
			}
		}
	}
	/**
	 * 拼接in语句
	 */
	@Override
	public String joinInSql(String estimateIds) {
		List<String> list = null;
		if(StringUtils.isNotBlank(estimateIds)) {
			if(estimateIds.contains(",")) {
				String[] split = estimateIds.split(",");
				list = new ArrayList<String>();
				for (String estimateId : split) {
					list.add(estimateId);
				}
				return SQLUtil.buildOracleSQLIn(list, 500, "TEI.ESTIMATE_ID");
			}else {
				return estimateIds;
			}
		}
		return estimateIds;
	}
}
